//
//  YWPostTroubleRecordsCell.m
//  maintain
//
//  Created by Kyo on 16/9/29.
//  Copyright © 2016年 ewin. All rights reserved.
//

#import "YWPostTroubleRecordsCell.h"
#import "UILabel+AttributedText.h"
#import "UIImageView+WebCache.h"
#import "YWCommonTool.h"
#import "YWHandler.h"
#import "YWMission.h"
#import "YWBuilding.h"
#import "YWBuildingManager.h"
#import "YWEquipmentManager.h"
#import "YWMissionManager.h"
#import "YWMacro.h"
#import "Masonry.h"
#import "YWReportTroubleModel.h"
#import "YWEquipment.h"
#import "YWLocation.h"
#import "YWContactManager.h"
#import "YWReplyManager.h"
#import "YWReply.h"

#import "UIColor+CustomColors.h"

@interface YWPostTroubleRecordsCell()
/** 状态Label */
@property (weak, nonatomic) UILabel *stateLabel;
/** 报障人头像 */
//@property (weak, nonatomic) UIImageView *reporterImageView;
/** 报障人 */
@property (weak, nonatomic) UILabel *reporterName;
/** 任务创建时间 */
@property (weak, nonatomic) UILabel *createTime;
/** 保障编号 */
@property (weak, nonatomic) UILabel *bianhao;
/** 设备类型 */
@property (weak, nonatomic) UILabel *equipmentType;
/** 设备位置 */
@property (weak, nonatomic) UILabel *location;
/** 报障描述 */
@property (weak, nonatomic) UILabel *note;
/** 报障现场图片 */
//@property (nonatomic, strong) NSArray *pictures;
/** 图片容器 */
//@property (weak, nonatomic) GropPictureView *picturesView;
@property (nonatomic, strong) NSString *stateString;

@end

@implementation YWPostTroubleRecordsCell

+ (instancetype)cellWithTableView:(UITableView *)tableView
{
    YWPostTroubleRecordsCell *cell = [tableView dequeueReusableCellWithIdentifier:YWPostTroubleRecordsCellIdentifier];
    if (cell == nil) {
        cell = [[YWPostTroubleRecordsCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:YWPostTroubleRecordsCellIdentifier];
    }
    return cell;
}

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        [self setUpSubviews];
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        //self.separatorInset = UIEdgeInsetsMake(0, SCREEN_WIDTH, 0, 0);
    }
    return self;
}

- (void)setReportTrouble:(YWReportTroubleModel *)reportTrouble{
    self.clipsToBounds = YES;
    _reportTrouble = reportTrouble;
    YWHandler *fromUser = nil;
    NSString *location = nil;
    
    if (reportTrouble.channel == YWPostTroubleTypeEwinApp) {
        fromUser = reportTrouble.reporter;
    }else{
        fromUser = [[YWHandler alloc] init];
        fromUser.userName = reportTrouble.troubleContact.contactName;
        fromUser.mobile = reportTrouble.troubleContact.contactNo;
    }
    
//    if (reportTrouble.equipment.equipmentId.length == 0) {
//        location = [[YWBuildingManager shareManager] areaLocationWithLocationId:reportTrouble.location.locationId];
//    }else{
//        YWEquipment* equipment = reportTrouble.equipment;
//        location = [[YWBuildingManager shareManager] equipmentLocation:equipment] ?: @"无";
//    }
    location = [[YWBuildingManager shareManager] areaLocationWithLocationId:reportTrouble.location.locationId];
    //    NSString* downloadUrl = [YWCommonTool pictureDownloadUrl:fromUser.headIcon];
    //    [_reporterImageView sd_setImageWithURL:[NSURL URLWithString:downloadUrl] placeholderImage:[UIImage imageNamed:@"profile_headimage"]];
    
    NSString *name = fromUser.userName.length?fromUser.userName:@"无";
    [_reporterName labelText:@"报障人: " withAttributedText:name andAttributedColor:[UIColor customYellowColor]];
    
    NSString* reportTimeStr = [YWCommonTool showTimeWithNormalFormatter:reportTrouble.reportTime / 1000];
    [_createTime labelText:@"报障时间: " withAttributedText:reportTimeStr andAttributedColor:[UIColor customYellowColor]];
    
    [_bianhao labelText:@"编号: " withAttributedText:[NSString stringWithFormat:@"%@",reportTrouble.troubleSequence?:@"无"] andAttributedColor:[UIColor customYellowColor]];
    
    [_equipmentType labelText:@"设备: " withAttributedText:reportTrouble.equipment.equipmentName ?:@"无" andAttributedColor:[UIColor blackColor]];
    
    
    [_location labelText:@"位置: " withAttributedText:location.length?location:@"无" andAttributedColor:[UIColor blackColor]];
    
    [_note labelText:@"说明: " withAttributedText:reportTrouble.note?:@"无" andAttributedColor:[UIColor blackColor]];
    
    //    _pictures = [[YWMissionManager shareManager] picturesWithTroubleMissionId:troubleMission.troubleId pictureTroubleType:YWPictureTroubleTypeMission];
    //    [_picturesView initWithGroupItems:_pictures withConstraint:nil];
    //任务参与人，要把报障人算进去
    NSInteger showCount = 1;
    NSInteger observerCount = reportTrouble.observers.count;
    NSMutableArray * observerMur = [NSMutableArray arrayWithArray:reportTrouble.observers];//将参与者拿出来
    NSMutableArray * observerIds = [NSMutableArray array];
    [observerMur enumerateObjectsUsingBlock:^(YWHandler* _Nonnull handler, NSUInteger idx, BOOL * _Nonnull stop) {
        [observerIds addObject:@(handler.uniqueId)];
    }];
    if (observerCount) {
        NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:@"%K = %ld", @"uniqueId", fromUser.uniqueId];
        NSArray *array = [[reportTrouble.observers filteredArrayUsingPredicate:searchPredicate] mutableCopy];
        if (array.count==1) {
            observerCount--;
            [observerIds removeObject:@(fromUser.uniqueId)];
        }
        showCount = showCount + observerCount;
    }
    NSString * firstStr = [NSString stringWithFormat:@"参与人(%ld): ",(long)showCount];
    
    [observerMur removeAllObjects];
    NSMutableString *observerName = [[NSMutableString alloc] init];
    if (observerIds.count) {
        for (id obj in observerIds ) {
            NSInteger uniqueId = [obj integerValue];
            YWHandler *handler = [[YWContactManager shareManager] getHandlerWithUniqueId:uniqueId];
            [observerMur addObject:handler];
        }
    }
    [observerMur enumerateObjectsUsingBlock:^(YWHandler*  _Nonnull handler, NSUInteger idx, BOOL * _Nonnull stop) {
        if (observerName.length && idx!=0) {
            [observerName appendString:@" "];
        }
        [observerName appendString:handler.userName];
    }];
    
    NSString * nameStr = [NSString stringWithFormat:@"%@ %@",name?:@"",observerName?:@""];//参与者要加进来
    
    self.observersLabel.attributedText = [YWCommonTool attributedTextWithFirstText:firstStr firstColor:[UIColor customTextGrayBlackColor] secondText:nameStr secondColor:[UIColor customBlueColor] font:kContentFont];
    //评论，如果没有评论，那么要重新设置约束
    //有评论
    NSArray *commentArray = [[YWReplyManager alloc] replysWithtRelationId:_reportTrouble.troubleId andRelationType:YWReplyRelationTypeTrouble];
    if (commentArray.count>0) {
        YWReply * reply = [commentArray firstObject];
        NSString * replyCount = [NSString stringWithFormat:@"评论(%ld): ",commentArray.count];
        //    时间
        NSString * timeStr = [YWCommonTool recordDateByFormatTimeString:reply.replyTime/1000 showYear:YES];
        //    内容
        
        NSString *atUserName = reply.atUser.userName.length>0?[NSString stringWithFormat:@" @%@",reply.atUser.userName]:@"";
        NSString * content = atUserName.length?[NSString stringWithFormat:@" %@  ",reply.content.length>0?reply.content:@""] : (reply.content.length>0?reply.content:@"");
        
        self.replyLabel.attributedText = [YWCommonTool attributedTextWithFirstText:replyCount firstColor:[UIColor customTextGrayColor] firstFont:kContentFont secondText:reply.replier.userName secondColor:[UIColor customBlueColor] secFont:kContentFont thirdText:atUserName thirdColor:[UIColor customBlueColor] thirdFont:kContentFont fourthText:content fourthColor:[UIColor blackColor] fourFont:kContentFont fifthText:timeStr fifthColor:[UIColor customTextGrayColor] fifthFont:[UIFont systemFontOfSize:13]];
    }else{
        self.replyLabel.attributedText = nil;
    }
    //任务状态Label
    _stateLabel.text = self.stateString;
    
    _equipmentType.preferredMaxLayoutWidth = _equipmentType.frame.size.width;
    _location.preferredMaxLayoutWidth = _location.frame.size.width;
    _note.preferredMaxLayoutWidth = _note.frame.size.width;
    self.observersLabel.preferredMaxLayoutWidth = self.observersLabel.frame.size.width;
    self.replyLabel.preferredMaxLayoutWidth = self.replyLabel.frame.size.width;
}

-(NSString *)stateString{
    YWTroubleMissionStatus state = _reportTrouble.troubleStatus;
    switch (state) {
        case YWTroubleMissionStatusUnAssign:
            _stateString = @"未分配";
            break;
        case YWTroubleMissionStatusAssign:
            _stateString = @"未完成";
            break;
        case YWTroubleMissionStatusFinish:
            _stateString = @"已完成";
            break;
        case YWTroubleMissionStatusCancelPostTrouble:
            _stateString = @"已取消";
            break;
    }
    return _stateString;
}


- (void)setUpSubviews {
    
    UIView *superview = self.contentView;
    /**
     *  头像 名字    状态
     *  头像 时间
     */
//    [self.reporterImageView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.and.top.mas_equalTo(superview).offset(8);
//        make.width.and.height.mas_equalTo(@46);
//    }];
    
    [self.reporterName mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.and.top.mas_equalTo(superview).offset(8);
        
    }];
    
    [self.createTime mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(_reporterName);
        make.top.mas_equalTo(_reporterName.mas_bottom).offset(4);
    }];
    
    [self.stateLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.baseline.mas_equalTo(_reporterName.mas_baseline);
        make.right.mas_equalTo(superview).offset(-8);
    }];
    /**
     *  编号
     *  设备
     *  位置
     *  说明
     *  图片集
     */
    [self.bianhao mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_createTime.mas_bottom).offset(6);
        make.left.mas_equalTo(superview).offset(8);
        make.right.mas_equalTo(superview).offset(-8);
    }];
    
    [self.equipmentType mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_bianhao.mas_bottom).offset(6);
    }];
    
    [self.location mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_equipmentType.mas_bottom).offset(6);
        
    }];
    
    [self.note mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_location.mas_bottom).offset(6);
        make.left.and.right.mas_equalTo(@[_bianhao,_equipmentType,_location]);
//        make.bottom.mas_equalTo(superview).offset(-8);
    }];
    [self.separatorLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_note.mas_bottom).offset(6);
        make.left.and.right.mas_equalTo(superview);
        make.height.mas_equalTo(@1.0);
    }];
    
    [self.observersLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.separatorLineView.mas_bottom).offset(6);
        make.left.and.right.mas_equalTo(_bianhao);
    }];
    [self.replyLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.observersLabel.mas_bottom).offset(6);
        make.left.and.right.mas_equalTo(_bianhao);
        make.bottom.mas_equalTo(superview).offset(-6);
    }];
    //    [self.picturesView mas_makeConstraints:^(MASConstraintMaker *make) {
    //        make.top.mas_equalTo(_note.mas_bottom).offset(6);
    //        make.left.and.right.mas_equalTo(@[_bianhao,_equipmentType,_location,_note]);
    //        make.height.mas_equalTo(@90);
    //        make.bottom.mas_equalTo(superview);
    //    }];
}

- (UILabel *)stateLabel{
    if (!_stateLabel) {
        UILabel *label = [[UILabel alloc] init];
        label.font = kContentFont;
        label.textColor = [UIColor blackColor];
        _stateLabel = label;
        [self.contentView addSubview:_stateLabel];
    }
    return _stateLabel;
}


- (UILabel *)reporterName{
    if (!_reporterName) {
        UILabel *label = [[UILabel alloc] init];
        label.font = kContentFont;
        label.textColor = [UIColor customTextGrayBlackColor];
        _reporterName = label;
        [self.contentView addSubview:_reporterName];
    }
    return _reporterName;
}

- (UILabel *)createTime{
    if (!_createTime) {
        UILabel *label = [[UILabel alloc] init];
        label.font = kContentFont;
        label.textColor = [UIColor customTextGrayBlackColor];
        _createTime = label;
        [self.contentView addSubview:_createTime];
    }
    return _createTime;
}

- (UILabel *)bianhao{
    if (!_bianhao) {
        UILabel *label = [[UILabel alloc] init];
        label.font = kContentFont;
        label.textColor = [UIColor customTextGrayBlackColor];
        _bianhao = label;
        [self.contentView addSubview:_bianhao];
    }
    return _bianhao;
}

- (UILabel *)equipmentType{
    if (!_equipmentType) {
        UILabel *label = [[UILabel alloc] init];
        label.font = kContentFont;
        label.numberOfLines = 0;
        label.textColor = [UIColor customTextGrayBlackColor];
        _equipmentType = label;
        [self.contentView addSubview:_equipmentType];
    }
    return _equipmentType;
}

- (UILabel *)location{
    if (!_location) {
        UILabel *label = [[UILabel alloc] init];
        label.font = kContentFont;
        label.numberOfLines = 0;
        label.textColor = [UIColor customTextGrayBlackColor];
        _location = label;
        [self.contentView addSubview:_location];
    }
    return _location;
}

- (UILabel *)note{
    if (!_note) {
        UILabel *label = [[UILabel alloc] init];
        label.font = kContentFont;
        label.numberOfLines = 0;
        label.textColor = [UIColor customTextGrayBlackColor];
        _note = label;
        [self.contentView addSubview:_note];
    }
    return _note;
}

@end
